<template>
  <div class="custom-timeline" ref="timelineContainer">
    <!-- 时间轴控件将在这里渲染 -->
    <div class="current-time-label" v-if="currentTimeLabel">
      {{ currentTimeLabel }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as Cesium from 'cesium'

// 定义组件属性
const props = defineProps({
  viewer: {
    type: Object,
    required: true
  }
})

// 获取DOM引用
const timelineContainer = ref(null)
const currentTimeLabel = ref('')
let timelineWidget = null
let clockSubscription = null

// 初始化时间轴控件
const initTimeline = () => {
  if (props.viewer && timelineContainer.value) {
    // 创建Cesium Timeline控件实例
    timelineWidget = new Cesium.Timeline(timelineContainer.value, props.viewer.clock)

    // 监听时间轴的settime事件，实现点击跳转功能
    timelineWidget.addEventListener('settime', handleTimelineClick, false)

    // 监听时间轴的setzoom事件
    timelineWidget.addEventListener('setzoom', handleTimelineZoom, false)

    // 订阅时钟变化来更新当前时间标签
    clockSubscription = props.viewer.clock.onTick.addEventListener(() => {
      currentTimeLabel.value = formatJulianDate(props.viewer.clock.currentTime)
     
    })

    // 监听时钟动画状态变化
    props.viewer.clock.onTick.addEventListener(() => {
      if (timelineWidget) {
        timelineWidget.updateFromClock()
      }
    })

    // 初始化当前时间标签
    currentTimeLabel.value = formatJulianDate(props.viewer.clock.currentTime)
    console.log('props.viewer.clock.currentTime', props.viewer.clock.currentTime, new Date(props.viewer.clock.currentTime))

    // 设置初始时间轴范围（当前时间前后各1小时）
    const currentTime = props.viewer.clock.currentTime;
    const startTime = Cesium.JulianDate.addHours(currentTime, -1, new Cesium.JulianDate());
    const endTime = Cesium.JulianDate.addHours(currentTime, 1, new Cesium.JulianDate());
    
    // 如果时间范围小于某个阈值（例如2小时），则适当放大时间范围以获得更好的刻度显示
    const spanSeconds = Cesium.JulianDate.secondsDifference(endTime, startTime);
    let adjustedStart = startTime;
    let adjustedEnd = endTime;

    if (spanSeconds < 7200) { // 2小时 = 7200秒
      const padding = (7200 - spanSeconds) / 2;
      adjustedStart = Cesium.JulianDate.addSeconds(startTime, -padding, new Cesium.JulianDate());
      adjustedEnd = Cesium.JulianDate.addSeconds(endTime, padding, new Cesium.JulianDate());
    }

    console.log('Initializing timeline with range:', { startTime: adjustedStart, endTime: adjustedEnd });
    timelineWidget.zoomTo(adjustedStart, adjustedEnd);

    // 添加窗口大小调整监听
    window.addEventListener('resize', handleResize)
  }
}

// 处理时间轴点击事件
const handleTimelineClick = (e) => {
  // 当用户点击时间轴时，设置当前时间为点击位置对应的时间
  if (props.viewer && e.timeJulian) {
    props.viewer.clock.currentTime = e.timeJulian

    // 可以在这里添加其他点击后的处理逻辑
    console.log('Timeline clicked at:', formatJulianDate(e.timeJulian))
  }
}

// 格式化Julian日期为易读的字符串
const formatJulianDate = (julianDate) => {
  
  if (!julianDate) return ''

  const gregorianDate = Cesium.JulianDate.toGregorianDate(julianDate)
  
  // 考虑时区偏移
  const timezoneOffset = new Date().getTimezoneOffset() * 60; // 获取本地时区偏移（秒）
  const adjustedHour = gregorianDate.hour - (timezoneOffset / 3600); // 调整小时
  
  const year = gregorianDate.year
  const month = String(gregorianDate.month).padStart(2, '0')
  const day = String(gregorianDate.day).padStart(2, '0')
  const hour = String(Math.floor(adjustedHour + 24) % 24).padStart(2, '0') // 确保小时在0-23范围内
  const minute = String(gregorianDate.minute).padStart(2, '0')
  const second = String(gregorianDate.second).padStart(2, '0')

  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 处理时间轴缩放事件
const handleTimelineZoom = (e) => {
  // 可以在这里处理时间轴缩放事件
  console.log('Timeline zoom event:', e)

  // 格式化时间显示
  if (e.startJulian && e.endJulian) {
    const formattedStartTime = formatJulianDate(e.startJulian);
    const formattedEndTime = formatJulianDate(e.endJulian);
    console.log('Zoom event times: start =', formattedStartTime, ', end =', formattedEndTime);
  }

  // 更新viewer的时钟范围
  if (props.viewer && e.startJulian && e.endJulian) {
    console.log('Updating viewer clock startTime and stopTime');
    props.viewer.clock.startTime = e.startJulian
    props.viewer.clock.stopTime = e.endJulian
  }
}

// 设置时间轴显示范围
const setTimelineRange = (startJulian, endJulian) => {
  console.log('setTimelineRange called with:', { startJulian, endJulian });

  // 格式化时间显示
  if (startJulian && endJulian) {
    const formattedStart = formatJulianDate(startJulian);
    const formattedEnd = formatJulianDate(endJulian);
    console.log('Formatted times: start =', formattedStart, ', end =', formattedEnd);
  }

  if (timelineWidget && startJulian && endJulian) {
    // 计算当前时间范围的秒数
    const spanSeconds = Cesium.JulianDate.secondsDifference(endJulian, startJulian);

    // 如果时间范围小于某个阈值（例如2小时），则适当放大时间范围以获得更好的刻度显示
    let adjustedStart = startJulian;
    let adjustedEnd = endJulian;

    if (spanSeconds < 7200) { // 2小时 = 7200秒
      const padding = (7200 - spanSeconds) / 2;
      adjustedStart = Cesium.JulianDate.addSeconds(startJulian, -padding, new Cesium.JulianDate());
      adjustedEnd = Cesium.JulianDate.addSeconds(endJulian, padding, new Cesium.JulianDate());
    }

    console.log('Calling timelineWidget.zoomTo with adjusted range');
    timelineWidget.zoomTo(adjustedStart, adjustedEnd);
  }
}

// 公开方法供父组件调用
defineExpose({
  setTimelineRange,

  // 添加高亮时间段的方法
  addHighlightRange: (color, heightInPx, base) => {
    if (timelineWidget) {
      // 检查base参数是否包含start和stop属性
      if (base && base.start && base.stop) {
        // 调用timelineWidget的addHighlightRange方法创建高亮范围对象
        const highlightRange = timelineWidget.addHighlightRange(color, heightInPx, 0);

        // 如果返回了高亮范围对象，则调用setRange方法设置时间范围
        if (highlightRange && typeof highlightRange.setRange === 'function') {
          highlightRange.setRange(base.start, base.stop);
          // 重新调整时间轴大小以显示高亮范围
          timelineWidget.resize();
          return highlightRange;
        }
      } else {
        console.error('Invalid base parameter for addHighlightRange:', base);
      }
    }
  }
})

// 处理窗口大小调整
const handleResize = () => {
  if (timelineWidget) {
    timelineWidget.resize()
  }
}

// 组件挂载时初始化时间轴
onMounted(() => {

  // 确保viewer已经初始化
  if (props.viewer) {
    initTimeline()
  } else {
    // 如果viewer尚未初始化，等待自定义事件
    window.addEventListener('cesiumInit', (e) => {

      if (e.detail && e.detail.viewer) {
        initTimeline()
      }
    })
  }
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (timelineWidget) {
    timelineWidget.destroy()
  }

  // 清理时钟订阅
  if (clockSubscription) {
    clockSubscription()
  }

  window.removeEventListener('resize', handleResize)
})
</script>

<style>
.custom-timeline {
  width: 100%;
  height: 100px;
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 100;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 为了确保时间轴控件的样式正确应用，导入Cesium的Timeline CSS */
@import '~cesium/Source/Widgets/Timeline/Timeline.css';

.current-time-label {
  position: absolute;
  top: 10px;
  right: 20px;
  color: white;
  font-size: 14px;

  padding: 5px 10px;
  border-radius: 4px;
  z-index: 10;
}

.cesium-timeline-main {
  height: 50px;

}
</style>